﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Sdari.Api.DbModel;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Sdari.Api.Gateway.Controllers
{
    [Authorize]
    public class ApiConsumerAccessController : Controller
    {
        private readonly ITokenServiceContext _db;
        private readonly ILogger<ApiConsumerAccessController> _logger;

        public ApiConsumerAccessController(ITokenServiceContext context, ILogger<ApiConsumerAccessController> logger)
        {
            _db = context;
            _logger = logger;
        }

        // GET: ApiConsumerAccesses
        public async Task<IActionResult> Index()
        {
            var tokenDbConnection = _db.ApiConsumerAccess.Include(a => a.ApiU).Include(a => a.ConsumerU);
            return View(await tokenDbConnection.ToListAsync());
        }

        // GET: ApiConsumerAccesses/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var apiConsumerAccess = await _db.ApiConsumerAccess
                .Include(a => a.ApiU)
                .Include(a => a.ConsumerU)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (apiConsumerAccess == null)
            {
                return NotFound();
            }

            return View(apiConsumerAccess);
        }

        // GET: ApiConsumerAccesses/Create
        public IActionResult Create()
        {
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address");
            ViewData["ConsumerUid"] = new SelectList(_db.ConsumerInfo, "Uid", "Secret");
            return View();
        }

        // POST: ApiConsumerAccesses/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ApiUid,ConsumerUid,Accessibility")] ApiConsumerAccess apiConsumerAccess)
        {
            if (ModelState.IsValid)
            {
                apiConsumerAccess.Uid = Guid.NewGuid();
                apiConsumerAccess.CreateDate = DateTime.Now;
                apiConsumerAccess.Creator = User.FindFirst("work_no")?.Value;
                _db.Add(apiConsumerAccess);
                await _db.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address", apiConsumerAccess.ApiUid);
            ViewData["ConsumerUid"] = new SelectList(_db.ConsumerInfo, "Uid", "Secret", apiConsumerAccess.ConsumerUid);
            return View(apiConsumerAccess);
        }

        // GET: ApiConsumerAccesses/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var apiConsumerAccess = await _db.ApiConsumerAccess.FindAsync(id);
            if (apiConsumerAccess == null)
            {
                return NotFound();
            }
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address", apiConsumerAccess.ApiUid);
            ViewData["ConsumerUid"] = new SelectList(_db.ConsumerInfo, "Uid", "Secret", apiConsumerAccess.ConsumerUid);
            return View(apiConsumerAccess);
        }

        // POST: ApiConsumerAccesses/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("Uid,Id,ApiUid,ConsumerUid,Accessibility")] ApiConsumerAccess apiConsumerAccess)
        {
            if (id != apiConsumerAccess.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _db.Attach(apiConsumerAccess);
                    var en = _db.Entry(apiConsumerAccess);
                    en.Property(nameof(apiConsumerAccess.ApiUid)).IsModified = true;
                    en.Property(nameof(apiConsumerAccess.ConsumerUid)).IsModified = true;
                    en.Property(nameof(apiConsumerAccess.Accessibility)).IsModified = true;
                    apiConsumerAccess.LastUpdatedDate = DateTime.Now;
                    apiConsumerAccess.LastUpdater = User.FindFirst("work_no")?.Value;
                    //_context.Update(apiConsumerAccess);
                    await _db.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ApiConsumerAccessExists(apiConsumerAccess.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["ApiUid"] = new SelectList(_db.ApiInfo, "Uid", "Address", apiConsumerAccess.ApiUid);
            ViewData["ConsumerUid"] = new SelectList(_db.ConsumerInfo, "Uid", "Secret", apiConsumerAccess.ConsumerUid);
            return View(apiConsumerAccess);
        }

        // GET: ApiConsumerAccesses/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var apiConsumerAccess = await _db.ApiConsumerAccess
                .Include(a => a.ApiU)
                .Include(a => a.ConsumerU)
                .FirstOrDefaultAsync(m => m.Id == id);
            if (apiConsumerAccess == null)
            {
                return NotFound();
            }

            return View(apiConsumerAccess);
        }

        // POST: ApiConsumerAccesses/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var apiConsumerAccess = await _db.ApiConsumerAccess.FindAsync(id);
            _db.ApiConsumerAccess.Remove(apiConsumerAccess);
            await _db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ApiConsumerAccessExists(int id)
        {
            return _db.ApiConsumerAccess.Any(e => e.Id == id);
        }
    }
}
